package com.xiao.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

import static java.lang.Thread.sleep;

/**
 * @author QuanZhao.Xiao
 * @description
 * @date 2022/1/24 18:55:36
 */
@RestController
@RequestMapping("pool")
@Slf4j
public class ThreadPoolController {
    /**
     * ThreadPoolExecutor
     */
    public static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
            10,
            20,
//            300,
            5L,
            TimeUnit.SECONDS,
//            new SynchronousQueue<>(),
            new LinkedBlockingQueue<>(200),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    /**
     * doExecute
     */
    @PostMapping
    public void doExecute() {
        int taskNumber = 300;
        for (int i = 0; i < taskNumber; i++) {
            poolExecutor.execute(() -> {
                //do some business ...
                try {
                    sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info(Thread.currentThread().getName() + " run");
            });
        }
    }
}
